/* 
search模块需要的action creator
*/
import { Dispatch } from "redux"
import { Users } from "../../api/model/searchTypes"

import { reqSearchUsers } from "../../api/search"

// 同步action
// 请求中
const requestingAction = () => ({ type: "REQUESTING" })
// 请求成功
const reqSuccessAction = (users: Users) => ({ type: "REQ_SUCCESS", data: users })
// 请求失败
const reqErrorAction = (msg: string) => ({ type: "REQ_ERROR", data: msg })

// 异步action 发ajax请求
export const searchAction = (searchName: string) => {
  return async (dispatch: Dispatch) => {
    // 分发 请求中的同步action
    dispatch(requestingAction())
    // 发搜索的ajax请求
    try {
      // 发 ajax请求
      const response = await reqSearchUsers(searchName)
      // 成功, 更新为成功的状态
      // 请求成功, 分发 请求成功的同步action
      dispatch(reqSuccessAction(response.data.items))
    } catch (error: any) {
      // 请求失败, 分发 请求失败的同步action
      dispatch(reqErrorAction(error.message || "未知错误"))
    }
  }
}
